<template>
  <view class="test-calendar-page">
    <!-- 状态栏占位 -->
    <view class="status-bar" :style="{ height: StatusBar + 'px' }"></view>

    <!-- 导航栏 -->
    <view class="nav-bar">
      <text class="back-btn" @tap="goBack">‹ 返回</text>
      <text class="title">日历组件测试</text>
    </view>

    <!-- 控制面板 -->
    <view class="control-panel">
      <view class="panel-title">控制面板</view>
      
      <!-- 模式切换 -->
      <view class="control-item">
        <text class="label">选择模式：</text>
        <view class="mode-buttons">
          <view 
            class="mode-btn" 
            :class="{ active: currentSelectMode === 'A' }"
            @tap="switchToModeA">
            创建状态
          </view>
          <view 
            class="mode-btn" 
            :class="{ active: currentSelectMode === 'B' }"
            @tap="switchToModeB">
            申请调用状态
          </view>
        </view>
      </view>

      <!-- 操作按钮 -->
      <view class="control-item">
        <view class="action-buttons">
          <button class="action-btn" @tap="clearAll">清空所有</button>
          <button class="action-btn" @tap="clearA">清空创建状态</button>
          <button class="action-btn" @tap="clearB">清空申请调用状态</button>
          <button class="action-btn" @tap="loadTestData">加载测试数据</button>
        </view>
      </view>

      <!-- 日期范围设置 -->
      <view class="control-item">
        <text class="label">最小日期：</text>
        <picker mode="date" :value="minDate" @change="onMinDateChange">
          <view class="picker-view">{{ minDate || '不限制' }}</view>
        </picker>
      </view>

      <view class="control-item">
        <text class="label">最大日期：</text>
        <picker mode="date" :value="maxDate" @change="onMaxDateChange">
          <view class="picker-view">{{ maxDate || '不限制' }}</view>
        </picker>
      </view>

      <!-- 显示月份数量 -->
      <view class="control-item">
        <text class="label">显示月份：</text>
        <picker :range="monthNumOptions" :value="monthNumIndex" @change="onMonthNumChange">
          <view class="picker-view">{{ monthNumOptions[monthNumIndex] }}个月</view>
        </picker>
      </view>

      <!-- 业务类型和产品类型设置 -->
      <view class="control-item">
        <text class="label">业务类型：</text>
        <picker :range="businessTypeOptions" :value="businessTypeIndex" @change="onBusinessTypeChange">
          <view class="picker-view">{{ businessTypeOptions[businessTypeIndex] }}</view>
        </picker>
      </view>

      <view class="control-item">
        <text class="label">产品类型：</text>
        <picker :range="productTypeOptions" :value="productTypeIndex" @change="onProductTypeChange">
          <view class="picker-view">{{ productTypeOptions[productTypeIndex] }}</view>
        </picker>
      </view>

      <!-- 测试场景快速设置 -->
      <view class="control-item">
        <text class="label">测试场景：</text>
        <view class="action-buttons">
          <button class="action-btn" @tap="setTestScenario1">二类组团业务</button>
          <button class="action-btn" @tap="setTestScenario2">三类研学活动</button>
        </view>
      </view>
    </view>

    <!-- 选中日期显示 -->
    <view class="selected-dates-panel">
      <view class="panel-title">选中日期</view>
      
      <view class="dates-section">
        <view class="dates-label">创建状态（蓝色）：</view>
        <view class="dates-list">
          <text 
            v-for="(date, index) in selectedDatesA" 
            :key="index" 
            class="date-tag date-tag-a">
            {{ date }}
          </text>
          <text v-if="selectedDatesA.length === 0" class="empty-text">暂无</text>
        </view>
      </view>

      <view class="dates-section">
        <view class="dates-label">申请调用状态（绿色）：</view>
        <view class="dates-list">
          <text 
            v-for="(date, index) in selectedDatesB" 
            :key="index" 
            class="date-tag date-tag-b">
            {{ date }}
          </text>
          <text v-if="selectedDatesB.length === 0" class="empty-text">暂无</text>
        </view>
      </view>

      <view class="dates-section">
        <view class="dates-label">统计信息：</view>
        <view class="stats">
          <text>创建状态：{{ selectedDatesA.length }} 个日期</text>
          <text>申请调用状态：{{ selectedDatesB.length }} 个日期</text>
          <text>总计：{{ selectedDatesA.length + selectedDatesB.length }} 个日期</text>
        </view>
      </view>
    </view>

    <!-- 自定义日历组件 -->
    <CustomCalendar
      :show="true"
      :selectMode="currentSelectMode"
      :defaultDateA="selectedDatesA"
      :defaultDateB="selectedDatesB"
      :minDate="minDate"
      :maxDate="maxDate"
      :monthNum="monthNum"
      colorA="#1677FF"
      colorB="#52c41a"
      :disabledDate="disabledDates"
      :showTitle="true"
      :showSubtitle="true"
      :pageInline="true"
      :businessType="businessType"
      :productType="productType"
      @dayClick="onDayClick"
      @change="onCalendarChange"
      @monthChange="onMonthChange"
    />

    <!-- 操作日志 -->
    <view class="log-panel">
      <view class="panel-title">
        操作日志
        <text class="clear-log" @tap="clearLog">清空</text>
      </view>
      <scroll-view class="log-content" scroll-y>
        <view 
          v-for="(log, index) in logs" 
          :key="index" 
          class="log-item">
          <text class="log-time">{{ log.time }}</text>
          <text class="log-text">{{ log.text }}</text>
        </view>
        <view v-if="logs.length === 0" class="empty-text">暂无日志</view>
      </scroll-view>
    </view>
  </view>
</template>

<script>
import CustomCalendar from '@/components/CustomCalendar.vue'

export default {
  components: {
    CustomCalendar
  },
  data() {
    return {
      StatusBar: 0,
      currentSelectMode: 'A', // 当前选择模式
      selectedDatesA: [], // A状态选中的日期
      selectedDatesB: [], // B状态选中的日期
      minDate: '', // 最小日期
      maxDate: '', // 最大日期
      monthNum: 3, // 显示月份数量
      monthNumOptions: [1, 2, 3, 4, 5, 6, 7, 12],
      monthNumIndex: 2, // 默认选择3个月
      businessType: 2, // 业务类型 (1: 一类商家, 2: 二类商家, 3: 三类商家)
      businessTypeOptions: ['一类商家', '二类商家', '三类商家'],
      businessTypeIndex: 1, // 默认二类商家
      productType: 4, // 产品类型 (1-泛营地接待, 2-综合研学业务, 3-目的地接待, 4-组团业务, 5-研学活动)
      productTypeOptions: ['泛营地接待', '综合研学业务', '目的地接待', '组团业务', '研学活动'],
      productTypeIndex: 3, // 默认组团业务
      logs: [] // 操作日志
    }
  },
  onLoad() {
    // 获取状态栏高度
    const systemInfo = uni.getSystemInfoSync();
    this.StatusBar = systemInfo.statusBarHeight || 0;

    // 设置默认日期范围（当前日期前后各3个月）
    const today = new Date();
    const minDate = new Date(today);
    minDate.setMonth(today.getMonth() - 3);
    const maxDate = new Date(today);
    maxDate.setMonth(today.getMonth() + 3);
    
    this.minDate = this.formatDate(minDate);
    this.maxDate = this.formatDate(maxDate);

    // 加载保存的数据
    this.loadSavedData();

    // 添加初始日志
    this.addLog('页面加载完成');
  },
  methods: {
    // 格式化日期为 YYYY-MM-DD
    formatDate(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },

    // 返回
    goBack() {
      uni.navigateBack();
    },

    // 切换到创建状态模式
    switchToModeA() {
      this.currentSelectMode = 'A';
      this.addLog('切换到创建状态模式');
    },

    // 切换到申请调用状态模式
    switchToModeB() {
      if (this.selectedDatesA.length === 0) {
        uni.showToast({
          title: '请先选择创建状态日期',
          icon: 'none',
          duration: 2000
        });
        return;
      }
      this.currentSelectMode = 'B';
      this.addLog('切换到申请调用状态模式');
    },

    // 清空所有
    clearAll() {
      this.selectedDatesA = [];
      this.selectedDatesB = [];
      this.addLog('清空所有选中日期');
    },

    // 清空创建状态
    clearA() {
      this.selectedDatesA = [];
      // 清空创建状态时，申请调用状态也应该清空（因为申请调用状态必须在创建状态范围内）
      this.selectedDatesB = [];
      this.addLog('清空创建状态日期');
    },

    // 清空申请调用状态
    clearB() {
      this.selectedDatesB = [];
      this.addLog('清空申请调用状态日期');
    },

    // 加载测试数据
    loadTestData() {
      const today = new Date();
      const testDatesA = [];
      const testDatesB = [];

      // 生成创建状态测试数据（未来7天）
      for (let i = 1; i <= 7; i++) {
        const date = new Date(today);
        date.setDate(today.getDate() + i);
        testDatesA.push(this.formatDate(date));
      }

      // 生成申请调用状态测试数据（从创建状态中选择前3天）
      testDatesB.push(...testDatesA.slice(0, 3));

      this.selectedDatesA = testDatesA;
      this.selectedDatesB = testDatesB;
      this.addLog(`加载测试数据：创建状态${testDatesA.length}个，申请调用状态${testDatesB.length}个`);
    },

    // 业务类型改变
    onBusinessTypeChange(e) {
      this.businessTypeIndex = e.detail.value;
      this.businessType = parseInt(e.detail.value) + 1; // 索引从0开始，业务类型从1开始
      this.addLog(`设置业务类型：${this.businessTypeOptions[this.businessTypeIndex]} (${this.businessType})`);
    },

    // 产品类型改变
    onProductTypeChange(e) {
      this.productTypeIndex = e.detail.value;
      this.productType = parseInt(e.detail.value) + 1; // 索引从0开始，产品类型从1开始
      this.addLog(`设置产品类型：${this.productTypeOptions[this.productTypeIndex]} (${this.productType})`);
    },

    // 设置测试场景1：二类组团业务
    setTestScenario1() {
      this.businessType = 2;
      this.businessTypeIndex = 1;
      this.productType = 4;
      this.productTypeIndex = 3;
      // 自动切换到B状态
      this.currentSelectMode = 'B';
      // 加载一些测试数据作为A状态
      const today = new Date();
      const testDatesA = [];
      for (let i = 1; i <= 10; i++) {
        const date = new Date(today);
        date.setDate(today.getDate() + i);
        testDatesA.push(this.formatDate(date));
      }
      this.selectedDatesA = testDatesA;
      this.selectedDatesB = [];
      this.addLog('设置测试场景：二类组团业务 (businessType=2, productType=4)，已切换到B状态，已加载A状态测试数据');
    },

    // 设置测试场景2：三类研学活动
    setTestScenario2() {
      this.businessType = 3;
      this.businessTypeIndex = 2;
      this.productType = 5;
      this.productTypeIndex = 4;
      // 自动切换到B状态
      this.currentSelectMode = 'B';
      // 加载一些测试数据作为A状态
      const today = new Date();
      const testDatesA = [];
      for (let i = 1; i <= 10; i++) {
        const date = new Date(today);
        date.setDate(today.getDate() + i);
        testDatesA.push(this.formatDate(date));
      }
      this.selectedDatesA = testDatesA;
      this.selectedDatesB = [];
      this.addLog('设置测试场景：三类研学活动 (businessType=3, productType=5)，已切换到B状态，已加载A状态测试数据');
    },

    // 最小日期改变
    onMinDateChange(e) {
      this.minDate = e.detail.value;
      this.addLog(`设置最小日期：${this.minDate}`);
    },

    // 最大日期改变
    onMaxDateChange(e) {
      this.maxDate = e.detail.value;
      this.addLog(`设置最大日期：${this.maxDate}`);
    },

    // 月份数量改变
    onMonthNumChange(e) {
      this.monthNumIndex = e.detail.value;
      this.monthNum = this.monthNumOptions[this.monthNumIndex];
      this.addLog(`设置显示月份数量：${this.monthNum}`);
    },

    // 禁用日期函数（示例：禁用周末）
    disabledDates({ year, month, date }) {
      const dateObj = new Date(year, month - 1, date);
      const day = dateObj.getDay();
      // 禁用周六和周日
      return day === 0 || day === 6;
    },

    // 日期点击事件
    onDayClick(dateStr, status, action) {
      this.addLog(`日期点击：${dateStr}，状态：${status}，操作：${action}`);
    },

    // 日历变化事件
    onCalendarChange(selectedA, selectedB) {
      this.selectedDatesA = selectedA;
      this.selectedDatesB = selectedB;
      this.addLog(`日历变化：创建状态${selectedA.length}个，申请调用状态${selectedB.length}个`);
    },

    // 月份切换事件
    onMonthChange(year, month) {
      this.addLog(`月份切换：${year}年${month}月`);
    },

    // 添加日志
    addLog(text) {
      const now = new Date();
      const time = `${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:${String(now.getSeconds()).padStart(2, '0')}`;
      this.logs.unshift({
        time,
        text
      });
      // 限制日志数量
      if (this.logs.length > 50) {
        this.logs = this.logs.slice(0, 50);
      }
    },

    // 清空日志
    clearLog() {
      this.logs = [];
      this.addLog('清空日志');
    },

    // 加载保存的数据
    loadSavedData() {
      try {
        const savedA = uni.getStorageSync('selectedDatesA');
        const savedB = uni.getStorageSync('selectedDatesB');
        if (savedA) {
          this.selectedDatesA = JSON.parse(savedA);
        }
        if (savedB) {
          this.selectedDatesB = JSON.parse(savedB);
        }
        if (savedA || savedB) {
          this.addLog('加载保存的数据');
        }
      } catch (e) {
        console.error('加载数据失败:', e);
      }
    },

    // 保存数据
    saveData() {
      try {
        uni.setStorageSync('selectedDatesA', JSON.stringify(this.selectedDatesA));
        uni.setStorageSync('selectedDatesB', JSON.stringify(this.selectedDatesB));
        this.addLog('数据已保存');
      } catch (e) {
        console.error('保存数据失败:', e);
      }
    }
  },
  onUnload() {
    // 页面卸载时保存数据
    this.saveData();
  }
}
</script>

<style lang="scss" scoped>
.test-calendar-page {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.status-bar {
  background-color: #1677FF;
}

.nav-bar {
  display: flex;
  align-items: center;
  padding: 20rpx;
  background-color: #1677FF;
  color: #ffffff;
  
  .back-btn {
    font-size: 32rpx;
    margin-right: 20rpx;
    padding: 10rpx;
  }
  
  .title {
    font-size: 36rpx;
    font-weight: 600;
  }
}

.control-panel {
  background-color: #ffffff;
  margin: 20rpx;
  padding: 30rpx;
  border-radius: 12rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.panel-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 20rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  
  .clear-log {
    font-size: 24rpx;
    color: #1677FF;
    font-weight: normal;
  }
}

.control-item {
  margin-bottom: 30rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
  
  .label {
    font-size: 28rpx;
    color: #666;
    margin-bottom: 15rpx;
    display: block;
  }
}

.mode-buttons {
  display: flex;
  gap: 20rpx;
}

.mode-btn {
  flex: 1;
  height: 70rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 8rpx;
  background-color: #f5f5f5;
  font-size: 28rpx;
  color: #666;
  transition: all 0.3s ease;
  
  &.active {
    background-color: #1677FF;
    color: #ffffff;
    font-weight: 600;
  }
  
  &:active {
    transform: scale(0.98);
  }
}

.action-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 15rpx;
}

.action-btn {
  flex: 1;
  min-width: 150rpx;
  height: 70rpx;
  line-height: 70rpx;
  background-color: #f5f5f5;
  color: #333;
  font-size: 26rpx;
  border: none;
  border-radius: 8rpx;
  
  &:active {
    background-color: #e0e0e0;
  }
}

.picker-view {
  padding: 15rpx 20rpx;
  background-color: #f5f5f5;
  border-radius: 8rpx;
  font-size: 28rpx;
  color: #333;
}

.selected-dates-panel {
  background-color: #ffffff;
  margin: 20rpx;
  padding: 30rpx;
  border-radius: 12rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.dates-section {
  margin-bottom: 30rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.dates-label {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 15rpx;
  font-weight: 500;
}

.dates-list {
  display: flex;
  flex-wrap: wrap;
  gap: 15rpx;
}

.date-tag {
  padding: 10rpx 20rpx;
  border-radius: 8rpx;
  font-size: 24rpx;
  color: #ffffff;
  
  &.date-tag-a {
    background-color: #1677FF;
  }
  
  &.date-tag-b {
    background-color: #52c41a;
  }
}

.empty-text {
  font-size: 24rpx;
  color: #999;
  font-style: italic;
}

.stats {
  display: flex;
  flex-direction: column;
  gap: 10rpx;
  
  text {
    font-size: 26rpx;
    color: #666;
  }
}

.log-panel {
  background-color: #ffffff;
  margin: 20rpx;
  padding: 30rpx;
  border-radius: 12rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  max-height: 400rpx;
}

.log-content {
  max-height: 300rpx;
}

.log-item {
  display: flex;
  gap: 15rpx;
  padding: 10rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
  
  &:last-child {
    border-bottom: none;
  }
}

.log-time {
  font-size: 22rpx;
  color: #999;
  min-width: 120rpx;
}

.log-text {
  font-size: 24rpx;
  color: #333;
  flex: 1;
}
</style>

